package com.specialtreasure.freightdepot.popupwindow;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.app.AlertDialog;
import android.text.InputFilter;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.app.core.util.XmlParser;
import com.specialtreasure.freightdepot.R;
import com.specialtreasure.freightdepot.adapter.PWTruckLengthAdapter;
import com.specialtreasure.freightdepot.model.StringSelect;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.ParserConfigurationException;


/**
 * Created by KUMA on 2017/7/25.
 * 车长车型
 */

public class SelectTruckPW extends PopupWindow {
    private Context mContext;
    private GridView gv_trucklength;
    private GridView gv_trucktype;
    private TextView tv_cancel;
    private TextView tv_ok;
    private List<StringSelect> dataTruckLength;
    private List<StringSelect> dataTruckType;
    private PWTruckLengthAdapter adapterTruckLength;
    private PWTruckLengthAdapter adapterTruckType;

    private OnResultListener mOnResultListener;
    private LinearLayout ll_car_length;
    private LinearLayout ll_car_type;
    private View view_line;
    String title;

    public SelectTruckPW(Context context) {
        super(context);
        this.mContext = context;
        init();
    }


    public SelectTruckPW(Context context,String title) {
        super(context);
        this.mContext = context;
        this.title=title;
        init();
    }


    private void init() {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(R.layout.pw_truck, null);
        gv_trucklength = (GridView) contentView.findViewById(R.id.gv_trucklength);
        gv_trucktype = (GridView) contentView.findViewById(R.id.gv_trucktype);
        tv_cancel = (TextView) contentView.findViewById(R.id.tv_cancel);
        tv_ok = (TextView) contentView.findViewById(R.id.tv_ok);
        ll_car_length = (LinearLayout) contentView.findViewById(R.id.ll_car_length);
        ll_car_type = (LinearLayout) contentView.findViewById(R.id.ll_car_type);
        view_line = (View) contentView.findViewById(R.id.view_line);




        //判断
        if (null!=title){
            if (title.equals("1")){//车长
                ll_car_length.setVisibility(View.VISIBLE);
                ll_car_type.setVisibility(View.GONE);
                view_line.setVisibility(View.GONE);
            }else if (title.equals("2")){//车型
                ll_car_type.setVisibility(View.VISIBLE);
                ll_car_length.setVisibility(View.GONE);
                view_line.setVisibility(View.GONE);

            }else {//车长加车型
                ll_car_length.setVisibility(View.VISIBLE);
                ll_car_type.setVisibility(View.VISIBLE);
                view_line.setVisibility(View.VISIBLE);
            }
        }


        dataTruckLength = new ArrayList<>();
        dataTruckType = new ArrayList<>();
        try {
            List<String> temp = XmlParser.parseTruckLength(mContext);
            for (String s : temp) {
                StringSelect ss = new StringSelect();
                ss.setStr(s);
                ss.setSelect(false);
                dataTruckLength.add(ss);
            }
            List<String> temp1 = XmlParser.parseTruckType(mContext);
            for (String s : temp1) {
                StringSelect ss = new StringSelect();
                ss.setStr(s);
                ss.setSelect(false);
                dataTruckType.add(ss);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
        adapterTruckLength = new PWTruckLengthAdapter(mContext, dataTruckLength);
        adapterTruckType = new PWTruckLengthAdapter(mContext, dataTruckType);
        gv_trucklength.setAdapter(adapterTruckLength);
        gv_trucklength.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final StringSelect ss = dataTruckLength.get(position);
                if (ss.getStr().equals("不限")) {
                    for (StringSelect strSelect : dataTruckLength) {
                        strSelect.setSelect(false);
                    }
                    ss.setSelect(true);
                    adapterTruckLength.notifyDataSetChanged();
                } else if (position == dataTruckLength.size() - 1) {
                    final EditText et = new EditText(mContext);
                    et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
                    new AlertDialog.Builder(mContext)
                            .setTitle("请输入内容（最多五个字）")
                            .setView(et)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    for (StringSelect strSelect : dataTruckLength) {
                                        strSelect.setSelect(false);
                                    }
                                    ss.setStr(et.getText().toString() + "米");
                                    ss.setSelect(true);
                                    adapterTruckLength.notifyDataSetChanged();
                                }
                            })
                            .setNegativeButton("取消", null)
                            .create()
                            .show();
                } else {
                    int i = 0;
                    for (StringSelect strSelect : dataTruckLength) {
                        if (strSelect.getStr().equals("不限")) {
                            strSelect.setSelect(false);
                        }
                        if (strSelect.isSelect()) {
                            i++;
                        }
                    }
                    StringSelect temp = dataTruckLength.get(dataTruckLength.size() - 1);
                    temp.setSelect(false);
                    temp.setStr("自定义");
                    boolean want = !ss.isSelect();
                    if (i < 3 || want == false) {
                        ss.setSelect(want);
                    } else {
                        Toast.makeText(mContext,"最多选择3个",Toast.LENGTH_SHORT);
                    }
                    adapterTruckLength.notifyDataSetChanged();
                }
            }
        });
        gv_trucktype.setAdapter(adapterTruckType);
        gv_trucktype.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                final StringSelect ss = dataTruckType.get(position);
                if (position == dataTruckType.size() - 1) {
                    final EditText et = new EditText(mContext);
                    et.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});
                    new AlertDialog.Builder(mContext)
                            .setTitle("请输入内容（最多五个字）")
                            .setView(et)
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    for (int i = 0; i < dataTruckType.size(); i++) {
                                        StringSelect strSelect = dataTruckType.get(i);
                                        strSelect.setSelect(false);
                                    }
                                    ss.setStr(et.getText().toString());
                                    ss.setSelect(true);
                                    adapterTruckType.notifyDataSetChanged();
                                }
                            })
                            .setNegativeButton("取消", null)
                            .create()
                            .show();
                } else {
                    for (int i = 0; i < dataTruckType.size(); i++) {
                        StringSelect strSelect = dataTruckType.get(i);
                        strSelect.setSelect(false);
                    }
                    ss.setSelect(true);
                    dataTruckType.get(dataTruckType.size() - 1).setStr("自定义");
                    adapterTruckType.notifyDataSetChanged();
                }
            }
        });

        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelectTruckPW.this.dismiss();
            }
        });

        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mOnResultListener != null) {
                    StringBuilder sb = new StringBuilder();
                    for (StringSelect ss : dataTruckLength) {
                        if (ss.isSelect()) {
                            sb.append(ss.getStr());
                        }
                    }
                    for (StringSelect ss : dataTruckType) {
                        if (ss.isSelect()) {
                            sb.append(ss.getStr());
                        }
                    }
                    mOnResultListener.onResult(sb.toString());
                    SelectTruckPW.this.dismiss();
                }
            }
        });
        // 设置SelectPicPopupWindow的View
        this.setContentView(contentView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        this.setFocusable(true);
        this.setOutsideTouchable(true);

//        // 刷新状态
//        this.update();
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);
        this.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    public void showAtBottom(View v) {
        this.showAtLocation(v, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
        backgroundAlpha(0.5f);
    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha) {
        Activity activity = (Activity) mContext;
        WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        activity.getWindow().setAttributes(lp);
    }

    public interface OnResultListener {
        public void onResult(String str);
    }

    public void setOnResultListener(OnResultListener OnResultListener) {
        this.mOnResultListener = OnResultListener;
    }
}
